﻿using BLL;
using BLL.Unit;
using Models;
using Models.Extension;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace YQFK.Controllers
{
    public class UnitController : ApiController
    {
        private UnitBLL unitbll = new UnitBLL();


        #region 保存单位管理(新增、修改)
        /// <summary>
        /// 保存单位管理(新增、修改)
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Unit/SaveUnit")]
        public async Task<object> SaveUnit(JObject json)
        {
            try
            {
                if (null != json)
                {
                    string res = JsonConvert.SerializeObject(json);
                    var dy = JsonConvert.DeserializeObject<dynamic>(res);
                    string userId = res.Contains("userId") ? dy.userId : string.Empty; //用户id
                    string UnitId = res.Contains("UnitId") ? dy.data.UnitId : string.Empty; //主键
                    string UnitName = res.Contains("UnitName") ? dy.data.UnitName : string.Empty; //单位名称
                    string ParentId = res.Contains("ParentId") ? dy.data.ParentId : string.Empty; //父节点id
                    string ParentSeqCode = res.Contains("ParentSeqCode") ? dy.data.ParentSeqCode : string.Empty; //父节点编码
                    string UnitType = res.Contains("UnitType") ? dy.data.UnitType : string.Empty; //单位类型
                    string Province = res.Contains("Province") ? dy.data.Province : string.Empty; //省份
                    string City = res.Contains("City") ? dy.data.City : string.Empty; //城市
                    string SortCode = res.Contains("SortCode") ? dy.data.SortCode : string.Empty; //排序号
                    bool isUpdataChild = false;
                    UnitModel model = new UnitModel();
                    
                    if (!string.IsNullOrEmpty(ParentSeqCode))
                    {
                        UnitModel parenModel = unitbll.GetEntityBySeqCode(ParentSeqCode);
                        if (null != parenModel)  //当父级标识码符合要求，ParentId
                        {
                            ParentId = parenModel.UnitId;
                        }
                        else  //查无此对象  赋值ParentSeqCode为空
                        {
                            ParentSeqCode = string.Empty;
                            return new { code = -1, count = 0, info = "上级单位不存在,请重新输入!" };
                        }
                    }
                    //存在对象
                    if (!string.IsNullOrEmpty(UnitId))
                    {
                        model = await unitbll.GetEntity(UnitId); //获取
                        if (null == model) 
                        {
                            return new { code = -1, count = 0, info = "当前单位已不存在,请重新确认!" };
                        }
                        //新增时，判断是否为相同单位
                        List<UnitModel> sameList = await unitbll.GetListByUnitName(UnitName.Trim());
                        sameList = sameList.Where(p => p.UnitId != UnitId).ToList();
                        if (sameList.Count() > 0)
                        {
                            return new { code = -1, count = 0, info = "单位已存在,请重新输入!" };
                        }
                        if (!string.IsNullOrEmpty(ParentSeqCode) && ParentSeqCode != model.ParentSeqCode)
                        {
                            model.UnitCode = await unitbll.GetUnitCode(ParentId); //单位编码,自动生成
                            isUpdataChild = true;
                        }
                        if (string.IsNullOrEmpty(ParentSeqCode))
                        {
                            ParentId = "0";
                            model.UnitCode = await unitbll.GetUnitCode(ParentId); //单位编码,自动生成
                            isUpdataChild = true;
                        }
                        model.ParentId = ParentId;
                        model.ParentSeqCode = ParentSeqCode;
                    }
                    else
                    {
                        //新增时，判断是否为相同单位
                        List<UnitModel> sameList = await unitbll.GetListByUnitName(UnitName.Trim());
                        if (sameList.Count() > 0) 
                        {
                            return new { code = -1, count = 0, info = "单位已存在,请重新输入!" };
                        }
                        model.ParentSeqCode = ParentSeqCode;
                        model.ParentId = ParentId;
                        //如果父节点为空
                        if (string.IsNullOrEmpty(ParentSeqCode))
                        {
                            model.ParentId = "0";
                        }
                        model.UnitCode = await unitbll.GetUnitCode(ParentId); //单位编码,自动生成
                        model.SequenceCode = await unitbll.GetRandomCode(); //序列码
                    }
                    model.UnitName = UnitName;
                    model.UnitType = UnitType;
                    model.Province = Province;
                    model.City = City;
                    model.SortCode = SortCode;
                    int count = await unitbll.SaveUnit(model);
                    if (count > 0)
                    {
                        //是否更新子节点
                        if (isUpdataChild)
                        {
                            await unitbll.UpdateChildUnitCode(model.UnitId); //更新子节点UnitCode
                        }
                        //新增操作
                        if (string.IsNullOrEmpty(UnitId))
                        {
                            new LoginUserBll().UpdateDepartInfo(model.UnitId, model.UnitName, userId);
                        }
                        return new { code = 0, count = 0, info = "保存成功!",data = model };
                    }
                    else
                    {
                        return new { code = -1, count = 0, info = "保存失败!" };
                    }
                }
                else {
                    return new { code = -1, count = 0, info = "参数不能为空!" };
                }
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }
        }
        #endregion

        #region 删除对象
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Unit/RemoveUnit")]
        public async Task<object> RemoveUnit(string unitId)
        {
            try
            {
                int count = await unitbll.RemoveUnit(unitId);
                if (count > 0)
                {
                    return new { code = 0, count = 0, info = "删除成功!" };
                }
                else
                {
                    return new { code = -1, count = 0, info = "删除失败!" };
                }
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }
        }
        #endregion

        #region 获取单位树结构
        /// <summary>
        /// 获取单位树结构
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Unit/GetTreeList")]
        public async Task<object> GetTreeList(string unitId = "")
        {
            string parentId = "0";//根节点
            try
            {
                //获取当前用户
                List<UnitModel> list = await unitbll.GetList(); //获取所有
                //用户传过来得
                if (!string.IsNullOrEmpty(unitId))
                {
                    var currentModel = await unitbll.GetEntity(unitId);
                    parentId = currentModel.ParentId;
                    list = list.Where(p => p.UnitCode.StartsWith(currentModel.UnitCode)).ToList();
                }
                List<UnitExModel> data = await GetUnitTreeData(list, parentId);

                return new { code = 0, count = 0, info = "获取成功!", data = data };
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }
        }
        #endregion


        #region 获取单位列表
        /// <summary>
        /// 获取单位列表
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [Route("api/Unit/GetUnitPageList")]
        [HttpGet]
        public async  Task<object> GetUnitPageList(JObject json)
        {
            try
            {
                if (null != json)
                {
                    string res = JsonConvert.SerializeObject(json);
                    var dy = JsonConvert.DeserializeObject<dynamic>(res);
                    int pageSize = res.Contains("pageSize")? Convert.ToInt32(dy.pageSize.ToString()):20;
                    int pageIndex = res.Contains("pageIndex") ? Convert.ToInt32(dy.pageIndex.ToString()) : 1;
                    string seqCode = res.Contains("seqCode") ? dy.data.seqCode.ToString() : "";
                    string unitCode = res.Contains("unitCode") ? dy.data.unitCode.ToString() : ""; //单位编码
                    string unitId = res.Contains("unitId") ? dy.data.unitId.ToString() : ""; //单位id
                    string unitName = res.Contains("unitName") ? dy.data.unitName.ToString() : "";
                    string tableName = "Unit";
                    string fieldNames = @"unitid,unitname,unitcode,sequencecode,parentid,parentseqcode,unittype,province,city,sortcode,remark ";
                    string sort = "asc";
                    string sidx = "unitcode";
                    string pkId = "unitid";
                    string strWhere = " 1=1";
                    //标识码
                    if (!string.IsNullOrEmpty(seqCode))
                    {
                        strWhere += string.Format(" and sequencecode like '%{0}%'", seqCode);
                    }
                    //单位名称
                    if (!string.IsNullOrEmpty(unitName))
                    {
                        strWhere += string.Format(" and unitname like '%{0}%'", unitName);
                    }
                    //单位编码
                    if (!string.IsNullOrEmpty(unitCode))
                    {
                        strWhere += string.Format(" and unitcode like '{0}%'", unitCode);
                    }
                    //单位id
                    if (!string.IsNullOrEmpty(unitId))
                    {
                        UnitModel curUnitModel = await unitbll.GetEntity(unitId);
                        strWhere += string.Format(" and unitcode like '{0}%'", curUnitModel.UnitCode);
                    }
                    int total = 0;
                    int records = 0;
                    DataTable dt = unitbll.GetDataTableByCondition(pageSize, pageIndex, tableName, pkId, fieldNames,
                   strWhere, sidx, sort, out total, out records);

                    return new { code = 0, count = records, info = "获取数据成功", data = dt };
                }
                else {
                    return new { code = -1, count = 0, info = "参数不能为空!", data = new { } };
                }
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }
        }
        #endregion

        #region 递归加载单位树
        /// <summary>
        /// 递归加载单位树
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public async Task<List<UnitExModel>> GetUnitTreeData(List<UnitModel> list, string parentId)
        {
            List<UnitExModel> data = new List<UnitExModel>();

            var rootlist = list.Where(p => p.ParentId == parentId);

            foreach (UnitModel entity in rootlist)
            {
                UnitExModel model = new UnitExModel();
                model.UnitId = entity.UnitId;
                model.UnitCode = entity.UnitCode;
                model.SequenceCode = entity.SequenceCode;
                model.UnitName = entity.UnitName;
                model.UnitType = entity.UnitType;
                model.Province = entity.Province;
                model.City = entity.City;
                model.Remark = entity.Remark;
                model.SortCode = entity.SortCode;
                model.ParentId = entity.ParentId;
                model.ParentSeqCode = entity.ParentSeqCode;
                model.IsParent = list.Where(p => p.ParentId == entity.UnitId).Count() > 0;
                model.Children = await GetUnitTreeData(list, model.UnitId);
                data.Add(model);
            }
            return data;
        }
        #endregion

        #region 获取当前对象
        /// <summary>
        /// 获取当前对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Unit/GetEntity")]
        public async Task<object> GetEntity(string unitId)
        {
            try
            {
                if (!string.IsNullOrEmpty(unitId))
                {
                    UnitModel data = await unitbll.GetEntity(unitId);
                    return new { code = 0, count = 0, info = "获取成功", data = data };
                }
                else
                {
                    return new { code = -1, count = 0, info = "获取失败" };
                }
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }

        }
        #endregion


        #region 获取随机验证码的对象
        /// <summary>
        /// 获取随机验证码的对象
        /// </summary>
        /// <param name="seqCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Unit/GetEntityBySeqCode")]
        public object GetEntityBySeqCode(string seqCode)
        {
            try
            {
                if (!string.IsNullOrEmpty(seqCode))
                {
                    UnitModel data =  unitbll.GetEntityBySeqCode(seqCode);

                    return new { code = 0, count = 0, info = "获取成功", data = data };
                }
                else
                {
                    return new { code = -1, count = 0, info = "获取失败" };
                }
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = ex.Message };
            }
        } 
        #endregion


        #region 获取全部单位
        /// <summary>
        /// 获取全部单位
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Unit/GetList")]
        public async Task<object> GetList()
        {
            List<UnitModel> data = await unitbll.GetList();

            return new { code = 0, count = 0, info = "获取成功", data = data };
        }
        #endregion
    }
}